package guitar

import (
	// "io"
	"encoding/csv"
	"net/http"

	"go-weixin/app/guitar/api/internal/logic/guitar"
	"go-weixin/app/guitar/api/internal/svc"
	"go-weixin/app/guitar/api/internal/types"

	"golang.org/x/text/encoding/simplifiedchinese"

	// "golang.org/x/text/transform"

	"github.com/zeromicro/go-zero/rest/httpx"
	xhttp "github.com/zeromicro/x/http"
)

func GuitarCsvHandler(svcCtx *svc.ServiceContext) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		var req types.GuitarCsvReq
		if err := httpx.Parse(r, &req); err != nil {
			xhttp.JsonBaseResponseCtx(r.Context(), w, err)
			return
		}

		l := guitar.NewGuitarCsvLogic(r.Context(), svcCtx)
		resp, err := l.GuitarCsv(&req)
		if err != nil {
			xhttp.JsonBaseResponseCtx(r.Context(), w, err)
		} else {
			svcCtx.Utils.HttpHeader.SetCsvHeader(w, req.FileName)
			gbkEncoder := simplifiedchinese.GBK.NewEncoder()
			writer := csv.NewWriter(gbkEncoder.Writer(w))
			//  writer.Write(resp.CsvData)
			writer.WriteAll(resp.CsvData)

			// writer := io.Writer(w)
			// writer.Write(resp.CsvData)
		}
	}
}
